﻿/*    
    This file is part of d-mixr.

    d-mixr is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    d-mixr is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with d-mixr.  If not, see <http://www.gnu.org/licenses/>.
*/

using CoreAudioApi;
using System;
using System.Text;

namespace Dmixr
{
    class AudioSystem : CoreAudioApi.Interfaces.IAudioSessionNotification
    {
        private static AudioSystem m_instance;

        public MMDevice DefaultDevice;
        public MMDeviceEnumerator DevEnum;

        // A delegate type for hooking up change notifications.
        public delegate void NewAudioSessionHandler();
        public event NewAudioSessionHandler NewAudioSessionEvent;

        private AudioSystem() {}

        public static void Init()
        {
            if (m_instance == null)
            {
                m_instance = new AudioSystem();
                m_instance.DevEnum = new MMDeviceEnumerator();
                m_instance.DefaultDevice = m_instance.DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

                m_instance.DefaultDevice.AudioSessionManager.RegisterSessionNotification(m_instance);  
            }
        }

        public static void Term()
        {
            if (m_instance != null)
            {
                m_instance.DefaultDevice.AudioSessionManager.UnregisterSessionNotification(m_instance);
                m_instance = null;
            }
        }

        public static AudioSystem Instance
        {
            get
            {
                return m_instance;
            }
        }

        public int OnSessionCreated(CoreAudioApi.Interfaces.IAudioSessionControl2 NewSession)
        {
            if (NewAudioSessionEvent != null)
                NewAudioSessionEvent();
            return 0;
        }
    }
}
